//
//  BJRefreshControl.swift
//  我的微博
//
//  Created by 李献红 on 15/10/18.
//  Copyright © 2015年 cn.lixianhong. All rights reserved.
//

import UIKit

/// 下拉偏移量
private let kRefreshPullOffset :CGFloat = -60
class BJRefreshControl: UIRefreshControl {
    
    
    //MARK: - KVO 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print(frame)
        
        //TODO:frame是self.frame,也就是刷新控件的frame
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
        
            print("翻过来")
           refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
        
            print("转过去")
            refreshView.rotateFlag = false
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    

    //MARK: - 构造函数
    override init() {
        super.init()
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //TODO:其实这两句一样的
//    required init?(coder aDecoder: NSCoder) {
////        fatalError("init(coder:) has not been implemented")
//        super.init(coder: aDecoder)
//        
//        setupUI()
//    }
    
    
    private func setupUI(){
        
        //KVO
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    
        //隐藏系统的转轮
        tintColor = UIColor.clearColor()
        
        //添加视图
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
    }
    
    /// 注销监听
    deinit {
    
        removeObserver(self, forKeyPath: "frame")
    }

    //MARK: - 懒加载控件
    private lazy var refreshView = BJRefreshView.refreshView()

}



///刷新视图
class BJRefreshView: UIView {
    
     /// 翻转标记
    private var rotateFlag = false {
    
        didSet {
        
            rotateAnimation()
        }
    }
    
     /// 提示图标
    
    @IBOutlet weak var loadIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var tipIcon: UIImageView!

    /// 从xib加载控件
    class func refreshView() -> BJRefreshView {
        return NSBundle.mainBundle().loadNibNamed("BJRefreshView", owner: nil, options: nil).last as! BJRefreshView
    }
    
    /// 旋转提示动画
    private func rotateAnimation() {
    
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        UIView.animateWithDuration(0.3) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    /// 开始加载动画
    private func startLoading() {
        if loadIcon.layer.animationForKey("loadingAnim") != nil {
            print("动画开始了")
            return
        }
    
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 2
        
        loadIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    
    /// 停止加载动画
    private func stopLoading() {
    
        tipView.hidden = false
        loadIcon.layer.removeAllAnimations()
    }
    
    
}